package nina.yiyou.salary.input.config


import nina.yiyou.salary.input.util.CellValueGetter
import nina.yiyou.salary.input.util.HeaderMapMaker
import org.apache.poi.ss.usermodel.Row
import org.apache.poi.ss.usermodel.Sheet
import org.apache.poi.ss.usermodel.Workbook

import java.time.LocalDateTime
import java.time.LocalTime
import java.util.stream.Collectors
import java.util.stream.IntStream

class WorkTimeSheetReader {

  interface Line {

    String department()

    LocalTime amIn()
  }

  WorkTimeSheetReader(Workbook excel) {
    _excel = excel
  }

  List<Line> read() {
    Sheet sheet = _excel.getSheetAt(1)
    Map<Integer, String> header = new HeaderMapMaker(sheet.getRow(0)).make()
    def getCellVal = { Row r, int c -> new CellValueGetter(r.getCell(c)).get() }

    return IntStream.rangeClosed(1, sheet.lastRowNum)
        .mapToObj { sheet.getRow(it) }
        .map { header.collectEntries { col, head -> [head, getCellVal(it, col)] } as Map }
        .map { makeLine(it) }
        .collect(Collectors.toList())
  }

  private Line makeLine(Map lineMap) {
    def amIn = lineMap['上班时间'] as LocalDateTime
    return new Line() {
      @Override
      String department() {
        return lineMap['部门']
      }

      @Override
      LocalTime amIn() {
        return amIn.toLocalTime()
      }
    }
  }

  private final Workbook _excel
}
